package master_worker;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by brossdong on 2018/1/24.
 * 重入锁
 */
public class UseLock {

    private Lock lock = new ReentrantLock();

    public void method1() {
        try {
            lock.lock();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "进入method1...");
            Thread.sleep(1000);
            System.out.println("当前线程:" + Thread.currentThread().getName() + "退出method1...");
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void method2() {
        try {
            lock.lock();
            System.out.println("当前线程:" + Thread.currentThread().getName() + "进入method2...");
            Thread.sleep(1000);
            System.out.println("当前线程:" + Thread.currentThread().getName() + "退出method2...");
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally { 
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        final UseLock useLock = new UseLock();

        Thread t1 = new Thread(new Runnable() {
            public void run() {
                useLock.method1();
                useLock.method2();
            }
        },"t1");
        t1.start();

        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
